/**
 * ResMania
 * More Information contact: info@resmania.com
 *
 * @package Core Framework Installation Helper Page JS
 * @version 0.5
 * @author webformatique
 * @copyright (C) 2010- webformatique
 * @license GNU/GPLv3 http://www.gnu.org/copyleft/gpl.html
 */

// JQuery config
jQuery.noConflict();
jQuery.ajax({timeout: 900000}); // set this to a high value for slow links

// define the image to use.
var okgif = "<img src='"+JPath+"components/com_resmania/installation/images/tick.png'>";
var failedgif = "<img src='"+JPath+"components/com_resmania/installation/images/cross.png'>";
var loadinggif = "<img src='"+JPath+"components/com_resmania/installation/images/ajax-loader.gif'>";
var warninggif = "<img src='"+JPath+"components/com_resmania/installation/images/warning.gif'>";
var timer;
var step2 = false;
var count = 0;
var sid = 0;
var canresume = 1;

// functions are in reverse order so they are correctly defined

/**
 * JQuery Hide/Show div function.
 */
function hideshow(div, state){
    if (!state){
        jQuery(div).toggle("fast");
    } else if (state=="fast") {
        jQuery(div).show("fast");
    } else {
        jQuery(div).hide("fast");
    }
}

// step 5
function installComplete(){
    document.getElementById("textpleasewait").style.display = "none";
    document.getElementById("textcomplete").innerHTML = "Installation Complete!<br /><a href=\'index.php?option=com_resmania\'>Click here to open the administrator console</a>";
}

// step 4
function CheckInstall(){

    document.getElementById("textcomplete").innerHTML = "Doing a quick check that all is installed properly...";
    var installcheckdiv = document.getElementById( "installcheck" );

    // change the page status icon
    installcheckdiv.innerHTML = loadinggif;

    // this does an installation QA
    jQuery.getJSON(RM_URL+"&act=install&task=postcheck",function(responseObject){

        if (responseObject.folderCheck === 1 && responseObject.dbCheck === 1){

            // change the page status icon
            installcheckdiv.innerHTML = okgif;

            installComplete(); // go to the next part
        } else {

            // change the page status icon
            installcheckdiv.innerHTML = failedgif;

            document.getElementById("textcomplete").innerHTML = "Installation Failed! More information can be found in the log file: /administrator/components/com_resmania/installation/install.log";

            alert("The Post Installation Checks Have Failed! Please check the log file /administrator/components/com_resmania/installation/install.log for further information.");
        }

    });

}

// step 3
function SetupDB(){

    // depending on the options selected the progressbar can be left showing, this jsut makes sure it's hidden
    document.getElementById("progressbar").style.display = "none";
    
    document.getElementById("textcomplete").innerHTML = "Configuring Database...";
    var dbsetupdiv = document.getElementById( "dbsetup" );

    // change the page status icon
    dbsetupdiv.innerHTML = loadinggif;

    var newdbInstall = document.getElementById( "dboverwrite" ).checked;

    // install the DB
    jQuery.getJSON(RM_URL+"&act=install&task=setupDB&new="+newdbInstall,function(responseObject){

        if (responseObject.success === 1){

            // change the page status icon
            dbsetupdiv.innerHTML = okgif;

            CheckInstall(); // go to the next part
        } else {

            // change the page status icon
            dbsetupdiv.innerHTML = failedgif;

            document.getElementById("textcomplete").innerHTML = "Installation Failed! More information can be found in the log file: /administrator/components/com_resmania/installation/install.log";

            alert("Database Configuration Failed! Please check the log file /administrator/components/com_resmania/installation/install.log for further information.");
        }

    });
}

// step 2
function downloadComplete(){

    document.getElementById("progressbar").style.display = "none";
    clearInterval(timer); // just make sure the downloadprogress is stopped

    document.getElementById("textcomplete").innerHTML = "Unzipping Core, Please Wait...";
    var unzipcorediv = document.getElementById( "unzipcore" );
   
    // change the page status icon
    unzipcorediv.innerHTML = loadinggif;

    // issue the Unzip command
    jQuery.getJSON(RM_URL+"&act=install&task=unzipcore&sid="+sid,function(responseObject){

        if (responseObject.success === 1){

            // change the page status icon
            unzipcorediv.innerHTML = okgif;
            SetupDB(); // go to the next part

        } else {

            unzipcorediv.innerHTML = failedgif; // change the page status icon
            document.getElementById("textcomplete").innerHTML = "Installation Failed! More information can be found in the log file: /administrator/components/com_resmania/installation/install.log";
            alert("Unzip Failed! Please check the log file /administrator/components/com_resmania/installation/install.log for further information.");
        }

    });
}

// called by step 1 timer
function downloadProgress(){
    // check the download progress
    var d=new Date(); // date is used to stop MSIE caching the page
    jQuery.getJSON(RM_URL+"&act=install&task=downloadprogress&sid="+sid+"&ts="+d.getTime(), function(responseObject){
        var progress = parseInt(responseObject.progress,10);
        var count = parseInt(responseObject.count,10);
        jQuery("#progressbar").progressbar( "option", "value", progress );
        document.getElementById("textcomplete").innerHTML = "download "+progress+"% complete";

        // after four loops (count starts at 0) the timer will be cancelled and
        // the next part of the process will run. This is protection for if the
        // ajax response does not reply.
        if (progress>=100 && count>9){
            clearInterval(timer);
            document.getElementById( "downloadstatus" ).innerHTML = okgif;
            downloadComplete(); // go to the next part
        }
    });
}

// step 1
function install(){

    // hide the installation button
    document.getElementById("nextbuttondiv").style.display = "none";
    document.getElementById("nextbuttondivmsg").style.display = "none";

    hideshow('#optionssection',"hide");

    // unhide the third step checks
    document.getElementById("step_3").style.display = "block";

    // display only the appropriate number icon
    document.getElementById("step_3_2icon").style.display = "block";

    jQuery("#progressbar").progressbar({
        value: 1
    });


    document.getElementById("textpleasewait").innerHTML = "ResMania is Installing Please Wait...";
    document.getElementById("textcomplete").innerHTML = "Downloading Core Started...";

    if (canresume === 1) {
        timer = window.setInterval('downloadProgress()', 4000); // run in 4 seconds
    }

    var resumeVar = document.getElementById("resumedownload").checked;

    // start the download
    jQuery.getJSON(RM_URL+"&act=install&task=download&resume=" + resumeVar + "&sid=" + sid,function(responseObject){

        if (responseObject.success === true){

            // change the page status icon
            document.getElementById( "downloadstatus" ).innerHTML = okgif;

            // hide the progressbar
            document.getElementById("progressbar").style.display = "none";

            // the download complete can also be triggered by the php response...
            clearInterval(timer);
            downloadComplete(); // go to the next part

        } else {

            if (!responseObject.license){
                clearInterval(timer);
                // show the installation button
                document.getElementById("nextbuttondiv").style.display = "block";
                document.getElementById("nextbuttondivmsg").style.display = "block";
                document.getElementById("step_3").style.display = "none";
                document.getElementById("step_3_2icon").style.display = "none";
                document.getElementById("textpleasewait").innerHTML = "";
                document.getElementById("textcomplete").innerHTML = "";
                alert("License key problem! The license key is invalid or has been installed on the maximum number of domains. Please purchase ResMania or contact ResMania customers services");
            } else {

                // change the page status icon
                document.getElementById( "downloadstatus" ).innerHTML = failedgif;
                document.getElementById("textcomplete").innerHTML = "Installation Failed! Please check the log file /administrator/components/com_resmania/installation/install.log for further information.";

                alert("Download Failed. Please ensure you are connected to the internet and try again!");
            }
        }
    });

}


function checkit(){

    document.getElementById( "unzip_help" ).innerHTML = "This indicates if the unzip of the core has passed or failed. More information can be found in the install log";
    document.getElementById( "dbsetup_help" ).innerHTML = "This indicates the status of the DB setup. More information can be found in the install log";
    document.getElementById( "check_help" ).innerHTML = "This is the status of the installation check, this checks if the Core has been installed ok, permissions and Database.";
    document.getElementById( "download_help" ).innerHTML = "This is the download status";
    document.getElementById( "php_help").innerHTML = "ResMania required PHP 5.2.5 or higher.";
    document.getElementById( "log_help").innerHTML = "Some of the PHP file access functions are blocked on your hosting! Such as the allow_url_fopen setting is disabled. The installation process uses this to write to the logfile and also for the download of the ResMania core. You can try to continue with this installation as it will try to download the ResMania core using PHP copy instead of fopen. However this might fail, if so you will need to ask your hosting providers to change the file access functions. Your apache error log should detail the function that is blocked in this case.";
    document.getElementById( "phpconfig_help").innerHTML = "PHP.ini recommended configuration requirements (these settings are to allow ResMania to operate well in all environments, such as slow network connections):-<br />max_execution_time = 240 (or higher)";
    document.getElementById( "core_reload_help").innerHTML = "Checking this option will reload the complete ResMania core framework. The latest Core Framework will be downloaded and will replace your installation in the RM folder.";
    document.getElementById( "db_reset_help").innerHTML = "This will restore the Database schema and values back to the default installation setup and values. It is irreversible so please don't check this unless you want to drop all data and settings. NOTE: if this is not checked the database will be upgraded in order to match the version required by the Core Framework.";
    document.getElementById( "click_to_expand_msg1" ).innerHTML = "Click to Expand/Collapse";
    document.getElementById( "click_to_expand_msg2" ).innerHTML = "Click to Expand/Collapse";
    document.getElementById( "resume_help" ).innerHTML = "By checking this the installer will reset the download and not continue to resume."
    var status = true;

    jQuery.getJSON(RM_URL+"&act=install&task=checks",function(responseObject){

        sid = responseObject.sid;

        // log (fopen ok?)
        if (responseObject.log === 1){
            document.getElementById( "logchkdiv" ).innerHTML = okgif;
        } else {
            document.getElementById( "logchkdiv" ).innerHTML = warninggif;
        }

        // php version check
        if (responseObject.php === 1){
            document.getElementById( "phpchkdiv" ).innerHTML = okgif;
        } else {
            document.getElementById( "phpchkdiv" ).innerHTML = failedgif;
            status = false;
        }

        // php optional check
        document.getElementById( "phpconfigchkdiv" ).innerHTML = okgif;
        if (responseObject.phpdirectivesoptional !== 1){
            document.getElementById( "phpconfigchkdiv" ).innerHTML = warninggif;
        }
        // php required check
        if (responseObject.phpdirectivesrequired !== 1){
            document.getElementById( "phpconfigchkdiv" ).innerHTML = failedgif;
            document.getElementById( "phpconfig_help").innerHTML = "ResMania requires the following PHP configuration:-<br/>memory_limit = 64 (or higher)<br />allow_url_fopen = On";
            status = false;
        }

        if (responseObject.pdosupport === 0 && responseObject.mysqli === 0){
            document.getElementById( "phpconfigchkdiv" ).innerHTML = failedgif;
            document.getElementById( "phpconfig_help").innerHTML = "ResMania requires either of the following DB drivers:-<br/>&nbsp;-&nbsp;PDO<br/>&nbsp;&nbsp;or<br/>&nbsp;-&nbsp;MySQLi<br/><br/>You need to install support for one of these PHP database drivers on your server in order to install and use ResMania.";
            status = false;
        }

        if (responseObject.zlibsupport === 0){
            document.getElementById( "phpconfigchkdiv" ).innerHTML = failedgif;
            document.getElementById( "phpconfig_help").innerHTML = "You do not have the zlib library installed! Please see http://php.net/manual/en/book.zlib.php this library is required so that zip files can be unzipped in PHP.";
            status = false;
        }

        // folder check
        if (responseObject.folder === 2){

            // return the ok gif
            document.getElementById( "folderchkdiv" ).innerHTML = okgif;
            document.getElementById( "folder_help" ).innerHTML = "The folder check has passed!";

            // this sets the folder overwrite value
            document.getElementById( "overwritecheckbox" ).innerHTML = "<div style=\'display:none;\'><input type=\'checkbox\' id=\'overwritecore\' name=\'overwritecore\' value=\'1\' checked></div>";

        } else if (responseObject.folder === 1) {
            // return the failed gif
            document.getElementById( "folderchkdiv" ).innerHTML = okgif;
            document.getElementById( "messagediv" ).innerHTML = "<br />Reset ResMania Core Framework<br /><span class='warningtext'>Checking this option will reset the ResMania Core Framework file system (all files within the RM folder). This is irreversible and you should ensure you have a file system backup prior to selecting this option.</span>";
            document.getElementById( "overwritecheckbox" ).innerHTML = "<input type=\'checkbox\' id=\'overwritecore\' name=\'overwritecore\' value=\'1\'>";
            document.getElementById( "folder_help" ).innerHTML = "The folder check has passed! However the ResMania core framework folder has been found. You can continue with the installation and overwrite the core by checking the checkbox below if you would like to perform a fresh installation. Please note at this time the existing core installation is unaffected.";
            step2 = true;
        } else if (responseObject.folder === 0) {
            // return the failed gif
            document.getElementById( "folderchkdiv" ).innerHTML = failedgif;
            status = false;
            document.getElementById( "folder_help" ).innerHTML = "The folder check has failed this could be because the installation process does not have permissions to create the `RM` folder or because this folder already exisits but is read-only. Please correct this problem then click re-check below";
        }

        // db check
        if (responseObject.db === 1){
            // return the ok gif
            document.getElementById( "dbchkdiv" ).innerHTML = okgif;
            document.getElementById( "db_help" ).innerHTML = "Your MySQL Database supports InnoDB";
        } else {
            // return the failed gif
            document.getElementById( "dbchkdiv" ).innerHTML = failedgif;
            status = false;
            document.getElementById( "db_help" ).innerHTML = "Your MySQL DB does not supports InnoDB. Please Check your DB setup or ask your webmaster/hosting provider about MySQL InnoDB support.";
        }

        // exisit DB version if any
        if (responseObject.db == "1" && responseObject.dbversion != "0"){
            document.getElementById( "dbmessagediv" ).innerHTML = "<br />Reset ResMania database<br /><span class='warningtext'>Checking this option will reset the ResMania database and restore the system to the default installation state. This is irreversible and you should ensure you have a database backup prior to selecting this option.</span>";
            document.getElementById( "dboverwritecheckbox" ).innerHTML = "<input type=\'checkbox\' id=\'dboverwrite\' name=\'dboverwrite\' value=\'1\'>";
            step2 = true;
        } else {
            // this sets the db overwrite value
            document.getElementById( "dboverwritecheckbox" ).innerHTML = "<div style=\'display:none;\'><input type=\'checkbox\' id=\'dboverwrite\' name=\'dboverwrite\' value=\'1\' checked></div>";
        }

        if (responseObject.zend_framework === 1){
            document.getElementById( "zf_check_div" ).innerHTML = okgif;
            if (responseObject.zend_framework_version !== '0'){
                document.getElementById( "zf_help" ).innerHTML = "You have Zend Framework version "+responseObject.zend_framework_version+" installed.";
            } else {
                document.getElementById( "zf_help" ).innerHTML = "Zend Framework is not installed on you server, Resmania will use an internal ZF library.";
            }
        } else {
            document.getElementById( "zf_check_div" ).innerHTML = failedgif;
            status = false;
            document.getElementById( "zf_help" ).innerHTML = "You have Zend Framework version "+responseObject.zend_framework_version+" installed. Resmania will work only with 1.10.6 version and above. You need to upgrade your Zend Framework library or disable it.";
        }

        if (responseObject.destinsize === 1){
            document.getElementById( "destinsize_div" ).innerHTML = okgif;
            document.getElementById( "destinsize_help" ).innerHTML = "The destination file size is readable - OK";
            if (responseObject.corezipexists === 1){document.getElementById( "resumeenabled" ).style.display = "block";}
            canresume = 1;
        } else {
            document.getElementById( "destinsize_div" ).innerHTML = failedgif;
            document.getElementById( "destinsize_help" ).innerHTML = "The system cannot determine the destination file size, this means download resume and the download progress will not be available. This could be related to permissions or ownership of the RM folder or that your configuration is locked down and does not support file functions.";
            canresume = 0;
        }
       
        if (!status){
            document.getElementById( "nextbuttondivmsg" ).innerHTML = "<b><span color=\'red\'>Initial Checks have FAILED! You must correct any errors above before you can continue the installation. The (?) icon will provide additional information why this has failed. NOTE: Installation is not complete. ResMania is NOT yet installed.</span></b>";
            document.getElementById( "nextbuttondiv" ).innerHTML = "<img src=\'"+JPath+"components/com_resmania/installation/images/recheck_button.gif\' onclick=\'checkit()\' style=\'cursor: pointer;\'>";
        } else {
            hideshow('#precheckssection',"hide");
            document.getElementById( "nextbuttondivmsg").innerHTML = "<span color=\'red\'>You MUST click <b />Install</b /> to complete this installation!</span>";
            document.getElementById( "nextbuttondiv" ).innerHTML = "<img src=\'"+JPath+"components/com_resmania/installation/images/install_button.gif\' onclick=\'install()\'>";
        }

    });
}
